package cn.qdu.controller;

import cn.qdu.dao.PostDao;
import cn.qdu.model.Post;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.qdu.dao.PostDao;
import cn.qdu.model.User;
import cn.qdu.service.PostService;
import org.apache.commons.io.FilenameUtils;

@WebServlet("/post/create")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
        maxFileSize = 1024 * 1024 * 10,      // 10 MB
        maxRequestSize = 1024 * 1024 * 50    // 50 MB
)
public class CreatePostServlet extends HttpServlet {

    private static final long MAX_FILE_SIZE = 1024 * 1024 * 10; // 10MB
    private static final long MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    // GET 请求（返回表单页面）保持不变
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/views/post/create_post.jsp").forward(req, resp);
    }

    // POST 请求（处理表单提交）
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 1. 从Session获取当前用户
            User currentUser = (User) request.getSession().getAttribute("currentUser");
            if (currentUser == null) {
                response.sendRedirect(request.getContextPath() + "/login?error=not_logged_in");
                return;
            }

            // 处理图片上传
            List<String> imagePaths = new ArrayList<>();
            String uploadDir = "uploads"; // Web 访问路径
            String realUploadDir = getServletContext().getRealPath(uploadDir);

            // 确保上传目录存在
            File uploadDirFile = new File(realUploadDir);
            if (!uploadDirFile.exists()) {
                uploadDirFile.mkdirs();
            }

            // 检查请求大小
            if (request.getContentLengthLong() > MAX_REQUEST_SIZE) {
                request.setAttribute("error", "请求内容过大，总大小不能超过50MB");
                request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
                return;
            }

            // 处理所有上传的文件
            for (Part part : request.getParts()) {
                if (part.getName().equals("images") && part.getSize() > 0) {

                    // 检查文件大小
                    if (part.getSize() > MAX_FILE_SIZE) {
                        request.setAttribute("error", "文件大小超过限制：单个文件不能超过10MB");
                        request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
                        return;
                    }

                    // 检查文件类型
                    String contentType = part.getContentType();
                    if (contentType == null || !contentType.startsWith("image/")) {
                        request.setAttribute("error", "只能上传图片文件");
                        request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
                        return;
                    }

                    // 生成安全的文件名
                    String submittedFileName = part.getSubmittedFileName();
                    String fileExtension = FilenameUtils.getExtension(submittedFileName);
                    String fileName = UUID.randomUUID().toString() + "." + fileExtension;

                    // 保存文件
                    Path savePath = Paths.get(realUploadDir, fileName);
                    Files.copy(part.getInputStream(), savePath, StandardCopyOption.REPLACE_EXISTING);

                    // 存储 Web 路径（如 "/uploads/filename.jpg"）
                    String webPath = uploadDir + "/" + fileName;
                    imagePaths.add(webPath);

                    System.out.println("[DEBUG] 图片已保存: " + savePath + ", 访问路径: " + webPath);
                }
            }

            // 3. 构建Post对象
            Post post = new Post();
            post.setUserId(currentUser.getUserId());
            post.setContent(request.getParameter("content"));
            post.setVisibility(request.getParameter("visibility"));
            post.setLocation(request.getParameter("location"));
            post.setImages(imagePaths);

            // 4. 调用Service保存数据
            PostService postService = new PostService();
            boolean success = postService.createPost(post);

            // 5. 返回响应
            if (success) {
                response.sendRedirect(request.getContextPath() + "/home");
            } else {
                request.setAttribute("error", "发布失败");
                request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "图片上传失败: " + e.getMessage());
            request.getRequestDispatcher("/views/post/create_post.jsp").forward(request, response);
        }
    }
}